package yns.springboot.security.sample.security.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;

import yns.springboot.security.sample.security.handler.FailureHandler;
import yns.springboot.security.sample.security.handler.SuccessHandler;
import yns.springboot.security.sample.security.service.SystemUserDetailService;

@Configuration
@EnableWebSecurity
@EnableMethodSecurity(prePostEnabled = true) //注解控制权限
public class SecurityConfig  {

	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private SystemUserDetailService systemUserDetailService;

	@Autowired
	private FailureHandler failureHandler;

	@Autowired
	private SuccessHandler successHandler;

	public void configure(AuthenticationManagerBuilder auth) throws Exception {
		auth.userDetailsService(systemUserDetailService);
	}

	@Bean
	public SecurityFilterChain urlConfigure(HttpSecurity http) throws Exception {

		http.authorizeHttpRequests((authorizeHttpRequests) -> authorizeHttpRequests
						.requestMatchers("/", "/index.html", "/js/**", "/css/**", "/template/**")
						.permitAll()
						.anyRequest()
						.authenticated())
				.formLogin((formLogin) -> formLogin
						.loginPage("/login.html")
						.permitAll()
						.successHandler(successHandler)
						.failureHandler(failureHandler)
						.loginProcessingUrl("/login"))
				.logout((logout) -> logout.logoutUrl("/index.html"))
				.csrf((csrf) -> csrf.disable());
		
		return http.build();
	}
	


	@Bean
	public PasswordEncoder passwordEncoder() {
		return new BCryptPasswordEncoder();
	}
}
